package com.bilibili.juc.volatiles;
/*
t1执行完a=1,t2开始执行b=1，结果：x = 1, y = 1;

t1先执行完之后，t2开始执行，结果：x = 0, y = 1;

t2先执行完之后，t1开始执行，结果：x = 1, y = 0;

但是通过多次实验会发现结果中出现 x = 0, y = 0的情况，仿佛t1的a = 1; 和t2的b = 1;互相之间不可见。这发什么了什么呢？


 */
public class TestVolatile2 {
    private static int x = 0, y = 0, a = 0, b = 0;

    public static void main(String[] args) throws Exception {
        while (true) {
            Thread t1 = new Thread(() -> {
                a = 1;
                x = b;
            });

            Thread t2 = new Thread(() -> {
                b = 1;
                y = a;
            });

            t1.start();t2.start();
            t1.join();t2.join();
            System.out.println("x = " + x);
            System.out.println("y = " + y);
            if(x==0&y==0){
                System.out.println("---------------------------------");
                System.out.println("x = " + x);
                System.out.println("y = " + y);
                System.out.println("---------------------------------");
            }
            if(x==0){
                System.out.println("---------------------------------");
                System.out.println("x = " + x);
                System.out.println("y = " + y);
                System.out.println("---------------------------------");
            }
            if(y==0){
                System.out.println("---------------------------------");
                System.out.println("x = " + x);
                System.out.println("y = " + y);
                System.out.println("---------------------------------");
            }
        }
    }
}